package ldh.im.admin.service;

import ldh.im.admin.dao.IUserDaoTest;
import ldh.im.base.dao.ImDepartmentDao;
import ldh.im.base.dao.ImUserDao;
import ldh.im.base.pojo.ImDepartment;
import ldh.im.base.pojo.ImUser;
import ldh.im.base.pojo.where.ImDepartmentWhere;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HistoryFigureService {

    @Resource
    private ImDepartmentDao departmentDao;
    @Resource
    private ImUserDao imUserDao;

    @Test
    public void parseFile() throws Exception {
        InputStream inputStream = this.getClass().getResourceAsStream("/names.txt");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = bufferedReader.readLine();

        ImDepartmentWhere where = new ImDepartmentWhere();
        where.setPageSize(100);
        where.setTenantCode("0002");
        where.setOrder("id.id asc");
        List<ImDepartment> departments = departmentDao.findByImDepartmentWhere(where);
        List<String> names = new ArrayList();
        Set<String> namesSet = new HashSet();
        int i = 0;
        int size = 0;
        while(line != null) {
            if (line.trim().equals("")) {
                if (names.size() > 1) {
                    size += names.size();
                    doBusiness(departments.get(i++), names, namesSet);
                    names.clear();
                }
            } else {
                String[] words = line.split("、");
                if (words.length == 1) {
                    words = line.split(" ");
                }
                names.addAll(Arrays.asList(words));
            }
            line = bufferedReader.readLine();
        }
        inputStream.close();
        System.out.println("size: " + size);
    }

    @Test
    public void listDepartments() {
        ImDepartmentWhere where = new ImDepartmentWhere();
        where.setPageSize(100);
        where.setTenantCode("0002");
        where.setOrder("id.id asc");
        List<ImDepartment> departments = departmentDao.findByImDepartmentWhere(where);
        System.out.println("size: " + departments.size());
    }

    private void doBusiness(ImDepartment department, List<String> names, Set<String> namesSet) throws Exception {
        for (String name : names) {
            if (namesSet.contains(name)) continue;
            namesSet.add(name);
            ImUser user = IUserDaoTest.buildUser(name, "0002", department.getCode());
            this.imUserDao.insert(user);
        }

    }
}
